import React, {Component,} from 'react';
import router from '../../util/router'
import storage from '../../util/storage';
import { request } from '../../util/request';
import { globalNotiInstance } from '../../notifiService'
import { BackHandler } from 'react-native';

export default class MWebview extends Component {
  /**
   * 在h5中执行JS代码
   * @param {*} jsCode
   */
  injectJavaScript = (jsCode) => {
    const webView = this.refs['webview_ref'];
    webView.injectJavaScript(jsCode);
  };

  /**
   * 关闭APP
   */
  finishAPP = () => {
    BackHandler.exitApp();
  };

  /**
   * 推送通知
   */
  pushLocalNotif = () => {
    globalNotiInstance.localNotif();
  }

  /**
   * HTTP 请求
   */
  request = (params) => {
    request(params.request).then(res => {
      if (params['success']) {
        let jsCode = `window.${params['success']}(${JSON.stringify(res)});`;
        this.injectJavaScript(jsCode);
      }
    }).catch(err => {
      if (params['fail']) {
        let jsCode = `window.${params['fail']}(${JSON.stringify(err)});`;
        this.injectJavaScript(jsCode);
      }
    })
  } 

  /**
   * 监听来自h5的消息
   * @param {*} event
   */
  handleMessage = (event) => {
    const message = event.nativeEvent;
    try {
      const payload = JSON.parse(message.data);
      let action = payload.action
      let params = payload.params;
      switch (action) {
        // 发送请求
        case 'request':
          this.request(params)
          break;
        // 本地通知
        case 'pushLocalNotif':
          this.pushLocalNotif();
          break;
        case 'finishAPP':
          this.finishAPP();
          break;
        default:
          console.log('未知消息', action)
      }
    } catch (e) {
      alert('调用APP方法参数错误！参数为：' + message.data);
    }
  };
}
